const db = require('../mongod/db');
const moment = require('moment');

const wenanCard = 'wenanCard'; // 文案集合

function errMongo(res) {
  res.send({
    isok: false,
    msg: '数据库错误！请联系后端！',
  });
  return;
}

// 文案增
function addWenan(req, res) {
  let query = req.body;
  query.id =
    moment(new Date()).format('YYYYMMDD') +
    Math.round(Math.random() * 899 + 100);
  query.createTime = moment(new Date()).format('YYYY-MM-DD');
  // eslint-disable-next-line
  db.insert(wenanCard, query, (err, result) => {
    if (err) {
      errMongo(err); //
      return;
    }
    let json = {
      success: true,
      code: 200,
      message: '添加成功',
    };
    res.send(json);
    return;
  });
}

// 账密查
function findAS(req, res) {
  // eslint-disable-next-line
  db.find(accountSecret, req.query, (err, result) => {
    if (err) {
      errMongo(err);
      return;
    }
    let json = {
      isok: true,
      code: 0,
      info: '查询成功',
      data: result,
    };
    res.send(json);
    return;
  });
}

// 账密删
function removeAS(req, res) {
  let query = req.query;
  // eslint-disable-next-line
  db.deleteInfo('deleteOne', accountSecret, query, (err, result) => {
    if (err) {
      errMongo(res);
      return;
    }
    let json = {
      isok: true,
      code: 0,
      info: '删除成功',
    };
    res.send(json);
    return;
  });
}

function updateAS(req, res) {
  let query = req.body;
  let condition = {
    // 条件
    id: query.id,
  };
  let newValue = {
    $set: query,
  };
  newValue.revise_time = new Date().getTime();
  // 方法，集合名，条件，更新内容
  // eslint-disable-next-line
  db.update('updateOne', userinfo, condition, newValue, (err, result) => {
    if (err) {
      errMongo(res);
      return;
    }
    let json = {
      isok: true,
      code: 0,
      info: '更新成功',
    };
    res.send(json);
    return;
  });
}

module.exports = {
  addWenan,
  findAS,
  removeAS,
  updateAS,
};
